var laguage = document.querySelectorAll(".language");
var choiceLanguage = document.querySelector("#choiceLanguage");

function styleC(){
    editor.setValue(`
#include <stdio.h>

int main(${params}){
    
}`);
    editor.setOption("mode","text/x-csrc")
}//C语言默认样式
function styleCadd() {
    editor.setValue(`class Solution {
public:
    int main(${params}) {
        
    }
};`);
    editor.setOption("mode","text/x-c++src")
}//C++默认样式
function styleJava() {
    editor.setValue(`
    public ${returnType} run(${params}){
             
    }`);
    editor.setOption("mode","text/x-java")
}//Java默认样式
function styleJavaScript() {
    editor.setValue(`var result = function() {
    
};`);
    editor.setOption("mode","javascript")
}//JS默认样式
//不同语言下，编译器高亮
for (var i= 0;i<laguage.length;i++) {
    laguage[i].onclick = function () {
        console.log(this.innerText);
        choiceLanguage.innerText = this.innerText;
        switch (choiceLanguage.innerText) {
            case "C":
                sendContent.judgeId = 1;
                styleC();
                break;
            case "Java":
                sendContent.judgeId = 8;
                styleJava();
                break;
            case "JavaScript":
                sendContent.judgeId = 11;
                styleJavaScript();
                break;
            case "C++":
                sendContent.judgeId = 4;
                styleCadd();
                break;
        }
    };
}

let app = document.querySelector("#app");
//在线编译器
let editor = CodeMirror.fromTextArea(app, {
    lineNumbers: true, //显示行数
    theme: 'idea',    //主题
    lint: true,

    spellcheck: true, //指定是否在输入上启用拼写检查。
    autocorrect: true, //指定是否在输入上启用自动更正。
    autocapitalize: true, //指定是否在输入上启用自动大写。

    tabSize: 4,
    // theme: "3024-night",
    styleActiveLine: true,
    line: true,
    foldgutter: true,
    gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter", "CodeMirror-lint-markers"],
    lineWrapping: true, //代码折叠         
    foldGutter: true,
    matchBrackets: true,  //括号匹配         
    autoCloseBrackets: true
});
//默认样式
styleC();


//点击返回竞赛
var back=document.querySelector("#return");
back.onclick=function () {
    window.history.go(-1);
};
//点击恢复默认样式
var backDefault = document.querySelector("#backDefault");
backDefault.onclick=function () {
     switch (choiceLanguage.innerText) {
         case "C": styleC();break;
         case "Java": styleJava();break;
         case "JavaScript": styleJavaScript();break;
         case "C++":styleCadd();break;
     }
};

var inputContent=sendContent.input[0].split(" ");
console.log(inputContent);
var before = new Number(inputContent[0]);
var end = new Number(inputContent[1]);
console.log(before);
console.log(end);
var javaTitle = `class Main{ public static void main(String args[]){
System.out.print(new Main().run(${before+","+end}));}`;
var javaFoot = `}`;
//点击执行代码
var performBtn = document.querySelector("#performBtn");

performBtn.onclick = function () {
    sendContent.src = javaTitle + editor.getValue().replace("\n", "\n\t") +javaFoot;
    console.log(sendContent.src);

    var ajax = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajax.open("POST",ROOTSources+"/contest/performCode",true);
    ajax.setRequestHeader("Content-Type", "application/json");
    ajax.send(JSON.stringify(sendContent));
    ajax.onreadystatechange = function () {
        if (ajax.readyState ===4) {
            if (ajax.status >= 200 && ajax.status < 300 || ajax.status === 304) {
                var jsonResult = JSON.parse(ajax.responseText);
                localStorage.setItem("recentCode",editor.getValue());
                if(jsonResult.globalMsg != null || jsonResult.result[0].status !== 0){
                    alert("对不起答案错误！");
                }else {
                    alert("执行正确，可提交")
                }
            }
        }
    }
};
//点击获取最近执行代码
var getRecentCode = document.querySelector("#getRecentCode");
getRecentCode.onclick=function () {
  editor.setValue(localStorage.getItem("recentCode"));
};
//点击提交代码
var submitCode=document.querySelector("#submitBtn");
submitCode.onclick=function () {
    sendContent.src = javaTitle + editor.getValue().replace("\n", "\n\t") +javaFoot;
    console.log(sendContent);
    var ajax = new XMLHttpRequest() || new ActiveXObject('Microsoft.XMLHTTP');
    ajax.open("POST",ROOTSources+"/contest/submitCode/"+contestMsgId+"/"+programId,true);
    ajax.setRequestHeader("Content-Type", "application/json");
    ajax.send(JSON.stringify(sendContent));
    ajax.onreadystatechange = function () {
        if (ajax.readyState ===4) {
            console.log("进来了");
            if (ajax.status >= 200 && ajax.status < 300 || ajax.status === 304) {
                console.log("提交");
                var jsonResult = JSON.parse(ajax.responseText);
                alert("代码已提交");
                window.history.go(-1);
            }
        }
    }
};

//防止页面跳转
// window.open('','','menubar=no');
// window.onblur=auto_submit;
// function auto_submit() {
//     alert("检测到您正在试图离开本网站，如果达到一定次数，将自动结束竞赛");
// }